<?php

namespace EthanZ\LaravelExt\Utils\Tools;

/**
 * 转换工具类
 */
class ConversionTools
{


    /**
     * 字符转换
     *
     * @param mixed  $var                数值
     * @param int    $decimals           小数位
     * @param string $thousandsSeparator 千分位
     *
     * @return string|null
     */
    public static function toNumber(mixed $var, int $decimals = 2, string $thousandsSeparator = ''): ?string
    {
        if (!is_numeric($var)) {
            return null;
        }

        if (is_string($var)) {
            // 千分位替换
            $var = str_replace(',', '', $var);
        }

        return number_format((float)$var, $decimals, '.', $thousandsSeparator);
    }


    /**
     * 10进制转36进制
     *
     * @param int $decimal 十进制值
     *
     * @return string
     */
    public static function decimalToBase36(int $decimal): string
    {
        if ($decimal < 0) {
            return '';
        }

        $map    = [
            '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H',
            'I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
        ];
        $base36 = '';
        do {
            $base36  = $map[($decimal % 36)] . $base36;
            $decimal /= 36;
        } while ($decimal >= 1);

        return $base36;
    }


    /**
     * 10进制转64进制
     *
     * @param int $decimal 十进制值
     *
     * @return string
     */
    public static function decimalToBase64(int $decimal): string
    {
        if ($decimal < 0) {
            return '';
        }

        $map    = [
            '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H',
            'I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
            'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
            's','t','u','v','w','x','y','z','_','='
        ];
        $base64 = '';
        do {
            $base64  = $map[($decimal % 64)] . $base64;
            $decimal /= 64;
        } while ($decimal >= 1);

        return $base64;
    }
}
